package com.smm.common;
import com.alibaba.fastjson.JSONObject;
import com.smm.data.Constants;
import com.smm.pojo.ExcelPojo;
import io.qameta.allure.Allure;
import io.restassured.RestAssured;
import io.restassured.config.LogConfig;
import io.restassured.response.Response;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Map;

import static io.restassured.RestAssured.given;

public class BaseTest {

    public static String logFilePath;


    public static Response requestBase(ExcelPojo pojo){

        // 获取参数
        String method = pojo.getMethod();
        String inputParams = pojo.getInputParams();
        String requestHeader = pojo.getRequestHeader();
        String url = pojo.getUrl();
        // 把请求头转换成Maps
        Map<String,Object>  headersMap = JSONObject.parseObject(requestHeader, Map.class);
        // 为每一个请求创建日志文件
        logFile(pojo);
        // 开始发送请求
        Response res = null;
        if("get".equalsIgnoreCase(method)){
            res = given().log().all().headers(headersMap).when().get(url).then().log().all().extract().response();
        }else if("post".equalsIgnoreCase(method)){
            res= given().log().all().headers(headersMap).body(inputParams).when().post(url).then().log().all().extract().response();
        }else if("patch".equalsIgnoreCase(method)){
            res= given().log().all().headers(headersMap).body(inputParams).when().patch(url).then().log().all().extract().response();
        }

        // 向Allure添加日志报告
        if (Constants.LOG_TO_FILE){
            try {
                Allure.addAttachment("接口请求响应信息",new FileInputStream(logFilePath));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    public static void logFile(ExcelPojo pojo){
        File dirPath = new File(System.getProperty("user.dir") + "/log" +pojo.getInterfaceModuleName());
        if(!dirPath.exists()){
            dirPath.mkdirs();
        }
        logFilePath =  dirPath +"\\test_"+ pojo.getCaseId() + ".log";
        PrintStream printStream = null;
        try {
             printStream = new PrintStream(logFilePath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        RestAssured.config = RestAssured.config().logConfig(LogConfig.logConfig().defaultStream(printStream));
    }

}
